﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using App2Wpf.ViewModels;


namespace App2Wpf.Views
{
    /// <summary>
    /// smallCard.xaml 的交互逻辑
    /// </summary>
    public partial class WritePixelsCard : BaseUserControl, ICardUC
    {
        public int ID { get; set; }
        public nameip connectNameip { get; set; }
        public System.Net.IPAddress iPAddress;

        ViewerPlus view;

        WriteableBitmap wBitmap;
        public WritePixelsCard(nameip serverinfo)
        {
            InitializeComponent();

            initLoading();

            connectNameip = serverinfo;

        }

        private void Close_Button_Click(object sender, RoutedEventArgs e)
        {
            view.session.CloseSession();
            ServiceLocator.rightWrapVM.removeCard(this);
        }

        public void initLoading()
        {
            LoadingG.Visibility = Visibility.Visible;
            MiniWindow.Visibility = Visibility.Hidden;
        }

        public void StartWork()
        {
            this.iPAddress = System.Net.IPAddress.Parse(connectNameip.ip);
            view = new ViewerPlus(iPAddress, connectNameip);

            view.OnConnect += () =>{
                Dispatcher.Invoke(new Action(() =>
                {
                    LoadingG.Visibility = Visibility.Collapsed;
                    MiniWindow.Visibility = Visibility.Visible;
                }));
            };
            view.onRendering += ViewWindow_refreshCard3;
            //准备画布
            PrepareForRendering(System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            Task.Run(() => view.init(iPAddress)); //后台线程

        }

        private void ViewWindow_refreshCard(byte[] tempBuffer, System.Windows.Int32Rect tempRect)
        {
            cardTitle.Text = view.VirtualDeskForm.cardTitle;

            // 调用线程无法访问此对象，因为另一个线程拥有该对象。  ==>  must use dispatcher...
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                this.wBitmap.Lock();
                System.Runtime.InteropServices.Marshal.Copy(tempBuffer, 0, this.wBitmap.BackBuffer, tempBuffer.Length);
                wBitmap.AddDirtyRect(tempRect);
                wBitmap.Unlock();
            }));

        }

        private void ViewWindow_refreshCard2(WriteableBitmap block, System.Windows.Int32Rect tempRect, byte[] buffer)
        {
            System.Windows.Point rectPoint = new System.Windows.Point(view.destPoint.X, view.destPoint.Y);

            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                cardTitle.Text = view.VirtualDeskForm.cardTitle;
                // 调用线程无法访问此对象，因为另一个线程拥有该对象。
                WriteableBitmap nblock = new WriteableBitmap(clientFunc.BytesToBitmapImage(buffer));

                Int32Rect nRect = new Int32Rect(view.destPoint.X, view.destPoint.Y, nblock.PixelWidth, nblock.PixelHeight);

                wBitmap.Lock(); //线程内对象才能锁住
                WriteableBitmapExtensions.Blit(wBitmap,
                    new System.Windows.Point(rectPoint.X, rectPoint.Y),    // 画布坐标点
                    nblock,                                                  // 输入 writeablebitmap    
                    new System.Windows.Rect(0, 0, nblock.Width, nblock.Height), //// 输入 writeablebitmap 的 RECT，实际内部只取用高度和宽度
                    Colors.White,
                    WriteableBitmapExtensions.BlendMode.None);
                wBitmap.AddDirtyRect(tempRect); //在图像未锁定时无法调用此方法

                wBitmap.Unlock();
                MiniWindow.Source = wBitmap;
            }));
            //MiniWindow.Source = wBitmap;
        }


        private void ViewWindow_refreshCard3(WriteableBitmap block, System.Windows.Int32Rect tempRect, byte[] buffer)
        {
            System.Drawing.Bitmap frame = view.frame;
            System.Drawing.Imaging.PixelFormat thePixelFormat = frame.PixelFormat;
            System.Drawing.Rectangle frameRect = new System.Drawing.Rectangle(0, 0, frame.Width, frame.Height);

            var bmpData = frame.LockBits(frameRect, System.Drawing.Imaging.ImageLockMode.ReadOnly, frame.PixelFormat);
            var bmpDataPtr = bmpData.Scan0;
            var bmpDataStride = bmpData.Stride;
            int bmpBufferSize = bmpDataStride * frame.Height;

            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                cardTitle.Text = view.VirtualDeskForm.cardTitle;
                // 调用线程无法访问此对象，因为另一个线程拥有该对象。
                Int32Rect RenderingRect = new Int32Rect(0, 0, frame.Width, frame.Height);
                wBitmap.Lock(); //线程内对象才能锁住
                wBitmap.WritePixels(RenderingRect, bmpDataPtr, bmpBufferSize, bmpDataStride, view.destPoint.X, view.destPoint.Y);
                wBitmap.AddDirtyRect(RenderingRect); //在图像未锁定时无法调用此方法
                wBitmap.Unlock();
                MiniWindow.Source = wBitmap;
            }));
        }

        private WriteableBitmap PrepareForRendering(System.Drawing.Imaging.PixelFormat bmpf)
        {
            PixelFormat pixelFormat = PixelFormats.Bgr24;
            switch (bmpf)
            {
                case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                    pixelFormat = PixelFormats.Bgra32;
                    break;
                case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
                    pixelFormat = PixelFormats.Bgr24;
                    break;

                case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
                    pixelFormat = PixelFormats.Indexed8;
                    break;
                // 添加其他需要转换的Pixformat枚举值
                default:
                    pixelFormat = PixelFormats.Default;
                    clientFunc.Showlog("unsupported pixel format");
                    break;
            }
            int DpiX = 96;
            int DpiY = 96;

            /// writeableBitmap 属性绑定
            /// System.ArgumentException: 必须在与 DependencyObject 相同的线程上创建 DependencySource。
            ////初始化对象 字节值 均为0 呈现为一个 大的黑色矩形
            wBitmap = new WriteableBitmap(1920,
                            1080, DpiX, DpiY, pixelFormat, null);
            return wBitmap;
        }

    }
}
